import React, { useEffect, useState } from 'react'
import './WriteContent.css'
import { List, NumberKeyboard, Button, Popup, Calendar, Toast, Selector, TextArea } from 'antd-mobile'
import TimeChange from '../../components/Times/TimeChange'
import { ScanningOutline, AppstoreOutline, TagOutline, CalendarOutline } from 'antd-mobile-icons'
import { useDispatch, useSelector } from 'react-redux'
import { userDetailAlter, userDetailAdd } from '../../redux//DetailSlice/DetailSlice'
import ajax from '../../api/ajax'

export default function WriteContent(props) {
    console.log('props', props);
    // 修改还是删除
    const { AlterOrAdd, activeIndex } = props
    const dispatch = useDispatch()
    // 获取store初始数据
    let oldItem = useSelector(state => state.WriteSliceReducer.WriteItems);
    let AlterItem = useSelector(state => state.WriteSliceReducer.AlterItem);
    // 获取定义的类型
    const option = useSelector(state => state.DetailSliceReducer.typeDetail);
    // 判断是修改还是添加，并获取修改前数据
    let WriteItems
    useEffect(() => {
        WriteItems = AlterOrAdd === '修改' ? AlterItem : oldItem
    }, [])
    console.log('AlterItem', AlterItem);
    const [time, setTime] = useState('')
    const [money, setMoney] = useState('')
    const [visible, setVisible] = useState('')

    // 类型表显示
    const [visible4, setVisible4] = useState(false)

    // 日期表
    const defaultSingle = new Date('2023-06-08')
    const [visible7, setVisible7] = useState(false)

    // 类型
    const [options, setOptions] = useState([])
    const [typeval, setTypeval] = useState([])

    // 备注
    const [remark, setRemark] = useState(null)

    // 商品名称
    const [shopName, setShopName] = useState(null)

    // id
    const [myid, setMyid] = useState('')
    const [userId, setUserId] = useState(null)
    // 获取数据后赋值
    useEffect(() => {
        // 一般异步数据在这里请求，然后set给变量
        setTypeval(WriteItems.type)
        setMoney(String(WriteItems.money))
        setTime(WriteItems.time)
        setRemark(WriteItems.remark)
        setShopName(WriteItems.name)
        setUserId(WriteItems.userId)
        setOptions(option)
        setMyid(AlterItem['fun'] === '修改' ? WriteItems.id : '')
    }, [])



    // 打开金额输入
    const openKeyboard = (name) => {
        setVisible(name)

    }
    // 关闭金额输入
    const onClose = () => {
        setVisible('')
        // 如果是正数的话，补全两个零+.  例如：25
        if (money.indexOf('.') === -1 && money.length !== 0) {
            setMoney(money + '.00')
        } else if (money.substring(money.indexOf('.')).length === 1) {
            // 例如：25.
            setMoney(money + '00')
        } else if (money.substring(money.indexOf('.')).length === 2) {
            setMoney(money + '0')
        }

    }
    // 确保两位小数的正数
    const reg = /^(([0-9]+)|([0-9]+\.[0-9]{0,2}))$/
    const moneyChange = (value) => {
        let x = money + value
        if (reg.test(x)) {
            setMoney(x)
        } else {
            Toast.show({
                content: '请输入两位小数的正数',
                afterClose: () => {
                },
            })
        }
    }

    // 金额删除功能
    const moneyDelete = () => {
        let newMoney = money.substring(0, money.length - 1);
        setMoney(newMoney)
    }

    // 更新被选中的类型
    const typeChange = (value, item) => {
        let x = item.label + ' > ' + value[0]
        setTypeval([item.label, value[0]])
    }
    // 备注内容
    const textChange = (value) => {
        setRemark(value)
    }
    // 店铺名称
    const shopNameChange = (value) => {
        setShopName(value)
    }
    // 记一笔提交
    const WriteSubmit = async () => {

        if (money == '' || time == '' || typeval == '') {
            Toast.show({
                icon: 'fail',
                content: '请正确填写信息',
            })
            return;
        }
        ;
        const NewWriteItems = {
            // billType: AlterItem.billType ? AlterItem.billType : activeIndex,
            billType: activeIndex,
            time,
            type: typeval,
            remark: remark ? remark:null,
            id: myid,
            shopName: shopName ? shopName : null,
            money: parseFloat(money),
            IdTime: new Date(),
            userId: JSON.parse(localStorage.getItem('userToken')).tel,
        }
        if (AlterOrAdd === '修改'){
            dispatch(userDetailAlter(NewWriteItems)) 
            
            const result = await ajax.post('/bill/updateBill', NewWriteItems)
            if (result.msg === 'success') {
                console.log('服务器修改请求完成');
            }
        }else{
            dispatch(userDetailAdd(NewWriteItems))
            console.log('修改发出请求', NewWriteItems);
            const result = await ajax.post('/bill/insertBill', NewWriteItems)
            if (result.msg === 'success') {
                console.log('服务器添加请求完成');
            }
        }

        Toast.show({
            icon: 'success',
            content: AlterOrAdd + '成功',
        })
    }
    return (
        <div className='WriteContent'>
            <div className='moneyShow'>
                <List className='moneyShowList'>
                    <List.Item onClick={() => openKeyboard('demo4')}>
                        {money === '' ? '0.00' : money}
                    </List.Item>
                </List>
                <div className='newTool'>
                    <Button
                        onClick={() => {
                            setVisible7(true)
                        }}
                    >
                        时间
                    </Button>
                    <div className='newToolPitcture'>
                        <ScanningOutline />
                    </div>
                </div>
            </div>
            <div className='ContentShow' >
                <div className='ContentShowItem' onClick={() => setVisible4(true)}>
                    <AppstoreOutline />
                    <span>分类</span>
                    {typeval[0] + '>' + typeval[1]}
                </div>
                <div className='ContentShowItem' onClick={() => {
                    setVisible7(true)
                }}>
                    <CalendarOutline />
                    <span>时间</span>
                    {time}
                </div>
                <div className='ContentShowItem' >
                    <TagOutline />
                    <span>店铺名称</span>
                    <TextArea
                        placeholder='......'
                        value={shopName == null ? '' : shopName}
                        // autoSize={{ minRows: 1, maxRows: 1 }}
                        rows={1}
                        className='TextArea'
                        onChange={(value) => shopNameChange(value)}
                    >{shopName == null ? '' : shopName}</TextArea>
                </div>
                <div className='ContentShowItem' >
                    <TagOutline />
                    <span>备注</span>
                    <TextArea
                        placeholder='......'
                        value={remark == null ? '' : remark}
                        rows={1}
                        autoSize={{ minRows: 1, maxRows: 4 }}
                        className='TextArea'
                        onChange={(value) => textChange(value)}
                    >{remark == null ? '' : remark}</TextArea>
                </div>
                <div className='ContentShowItem' >
                    <Button block size='large' type='submit' onClick={WriteSubmit} className='WriteButoon'>
                        {AlterOrAdd === '修改' ? '更新数据 √' : '记一笔  √'}
                    </Button>
                </div>
            </div>
            {/* 类型 */}
            <Popup
                visible={visible4}
                showCloseButton
                onClose={() => {
                    setVisible4(false)
                }}
                onMaskClick={() => {
                    setVisible4(false)
                }}
            >
                <div
                    style={{ height: '40vh', overflowY: 'scroll', padding: '10px 20px' }}
                >

                    {
                        options.map(item => {
                            return <div className='DetailTopTypeContent' key={item.label}>
                                <span className='DetailTopTypeTitle'>{item.label}</span>
                                <Selector
                                    columns={3}
                                    options={item.children}
                                    defaultValue=''
                                    value={typeval == '选择类型' ? '' : typeval}
                                    onChange={(value) => typeChange(value, item)}
                                    style={{
                                        '--border-radius': '80px',
                                        '--border': 'solid transparent 1px',
                                        '--checked-border': 'solid var(--adm-color-primary) 1px',
                                        '--padding': '8px 4px',
                                    }}
                                />
                            </div>
                        })
                    }
                </div>
            </Popup>
            {/* 日期 */}
            <Popup
                visible={visible7}
                showCloseButton
                onClose={() => {
                    setVisible7(false)
                }}
            >
                <Calendar
                    selectionMode='single'
                    defaultValue={defaultSingle}
                    onChange={val => {
                        // console.log(val)
                        setTime(TimeChange(val))
                    }}
                />
            </Popup>

            <NumberKeyboard
                visible={visible === 'demo4'}
                onClose={onClose}
                customKey={['.']}
                confirmText='确定'
                onInput={(value) => moneyChange(value)}
                onDelete={() => moneyDelete()}
            />
        </div>
    )
}
